package com.demo.stock.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis配置
 *
 * @author admin
 */
@Configuration
public class JedisConfiguration {
    @Value("${spring.redis.host:null}")
    private String host;

    @Value("${spring.redis.port:6379}")
    private int port;

    @Value("${spring.redis.timeout:100000}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-idle:200}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.max-wait:10000}")
    private long maxWaitMillis;

    @Value("${spring.redis.password:}")
    private String password;

    @Value("${spring.redis.block-when-exhausted:true}")
    private boolean blockWhenExhausted;

    @Bean
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);
        JedisPool jedisPool;
        String nullValue = "null";
        if (StringUtils.isNotBlank(host) && !nullValue.equals(host)) {
            if (StringUtils.isNotBlank(password)) {
                jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
            } else {
                jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
            }
            return jedisPool;
        }else{
            return null;
        }
    }
}
